import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
// axios.defaults.baseURL = 'http://localhost:8080/'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '',
    selectedKey: 1
  },
  mutations: {
    initList (state, item) {
      state.list = item
    },
    setInputValue (state, val) {
      state.inputValue = val
    },
    // 添加列表项目
    addItem (state) {
      var id
      if (state.list.length === 0) {
        id = 1
      } else {
        id = state.list[state.list.length - 1].id + 1
      }
      const obj = {
        id,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.inputValue = ''
    },
    // 删除
    remove (state, id) {
      var index = state.list.findIndex(item => item.id === id)
      state.list.splice(index, 1)
    },
    // 复选框
    stateChange (state, id) {
      var index = state.list.findIndex(item => item.id === id)
      state.list[index].done = !state.list[index].done
    },
    changeKey (state, key) {
      state.selectedKey = key
    },
    // 清除已完成
    clearDone (state) {
      state.list = state.list.filter(item => item.done === false)
    }
  },
  actions: {
    getList (context) {
      axios.get('list.json').then(({ data }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    leftNumber (state) {
      // filter 筛选数组将符合的条件的组成新数组
      return state.list.filter(item => item.done === false).length
    },
    // 分情况战士
    selectedList (state) {
      if (state.selectedKey === 1) {
        return state.list
      } else if (state.selectedKey === 2) {
        return state.list.filter(item => item.done === false)
      } else {
        return state.list.filter(item => item.done === true)
      }
    }
  }
})
